<script setup lang="ts">
	import { ref, onMounted } from "vue"
	import { cloneDeep } from 'lodash-es'
	import { getCategoryFilterInfo, getQueryByFilter } from '@/api/irrigationDistrictMap.js';
	const showBottom = ref(false)
	const activeName = ref("")

	let queryListHistory = [];
	let dataListHistory = [];

	// 定义菜单数据
	const menuData = ref([]);
	// 选中的过滤项
	const selectedFilters = ref({});
	// 全选状态
	const checkAllMap = ref<Record<string, boolean>>({});

	// 半选状态
	const isIndeterminateMap = ref<Record<string, boolean>>({});

	//历史选择状态 点击取消时使用
	let oldCheckAllMap = {}

	let oldIsIndeterminateMap = {}

	let oldSelectedFilters = {}
	//-----
	menuData.value.forEach((category) => {
		selectedFilters.value[category.type] = [];
		checkAllMap.value[category.type] = false;
		isIndeterminateMap.value[category.type] = false;
	});
	// 初始化每个分类的选中状态
	menuData.value.forEach((category) => {
		selectedFilters.value[category.type] = [];
	});

	// 处理全选事件
	const handleCheckAllChange = (categoryType : string, isChecked : boolean, detailList : any[]) => {

		if (!!detailList) {
			selectedFilters.value[categoryType] = isChecked ? detailList.map((item) => item.itemType) : [];
		} else {
			selectedFilters.value[categoryType] = isChecked;
		}
		isIndeterminateMap.value[categoryType] = false;
		checkAllMap.value[categoryType] = isChecked;

	};
	// 处理复选框变化，更新半选和全选状态
	const handleCheckboxChange = (categoryType : string, values : string[], detailList ?: any[]) => {
		const total = detailList ? detailList.length : menuData.value.find((item) => item.type === categoryType)?.detail.length || 0;
		const checkedCount = values.length;
		checkAllMap.value[categoryType] = checkedCount === total;
		isIndeterminateMap.value[categoryType] = checkedCount > 0 && checkedCount < total;
		selectedFilters.value[categoryType] = values;

	};
	// 处理菜单打开事件
	const handleOpen = (key : string) => {
		console.log(`打开菜单: ${key}`);
	};

	// 处理菜单关闭事件
	const handleClose = (key : string) => {
		console.log(`关闭菜单: ${key}`);
	};

	// 定义事件
	const emits = defineEmits(['filterChange']);
	//增加
	const addNewData = async (queryList) => {
		const  data  = await getQueryByFilter(queryList);
		dataListHistory = [...dataListHistory, ...data];
	};
	const getQueryByFilteList = async (result) => {
	let newQueryList = [];
		Object.keys(result).map((key) => {
			if (typeof result[key] === 'boolean') {
				//如果是一级
				newQueryList.push({
					type: key,
				});
			} else {
				//如果是二级
				const requests = result[key].map((item) => {
					return {
						type: key,
						itemType: item,
					};
				});
				newQueryList.push({
					type: key,
					requests,
				});
			}
		});
		const { added, removed } = diffArrays(queryListHistory, newQueryList);
			if (added.length>0) {
				await addNewData(added);
			}
			if (removed.length>0) {
				// 先删除再新增
				dataListHistory = removeByDiff(dataListHistory, removed);
			}

		emits('filterChange', dataListHistory);
		queryListHistory = newQueryList;

		};

	// 发送过滤变化事件
	const emitFilterChange = async () => {

		const result = Object.entries(selectedFilters.value).reduce((acc, [categoryType, items]) => {
			if (items.length > 0|| items === true) {
				acc[categoryType] = items;
			}
			return acc;
		}, {});
		console.log("执行3")
		await getQueryByFilteList(result);
	};

	// 从API获取数据（如果需要）
	const getCategoryFilterInfoDetail = () => {
		getCategoryFilterInfo().then((data) => {

			if (data && data.length > 0) {
				menuData.value = data;
				// 重新初始化选中状态
				menuData.value.forEach((category) => {
					selectedFilters.value[category.type] = [];
				});
			}
		});
	};

	const comInit = () => {
		// 如果需要从API获取数据，取消下面的注释
		getCategoryFilterInfoDetail();
	};

	const commit = async () => {
		console.log("执行1")
		showBottom.value = false
		uni.showLoading({
			title: '加载中',
			mask: true
		});
		try {
			console.log("执行2")
			await emitFilterChange()
		} catch (e) {
			console.error("报错了", e)
		} finally {
			uni.hideLoading();
		}

	}

	//取消，恢复打开时选项，关闭弹窗
	const close = () => {
		showBottom.value = false
		checkAllMap.value = cloneDeep(oldCheckAllMap)
		isIndeterminateMap.value = cloneDeep(oldIsIndeterminateMap)
		selectedFilters.value = cloneDeep(oldSelectedFilters)

	}

	//打开时从历史里面拿取数据
	const openPop = () => {
		oldCheckAllMap = cloneDeep(checkAllMap.value)
		oldIsIndeterminateMap = cloneDeep(isIndeterminateMap.value)
		oldSelectedFilters = cloneDeep(selectedFilters.value)
		showBottom.value = true
	}

	onMounted(() => {
		comInit();
	});


	defineExpose({
		openPop
	})
	
	//对比二维数组 得到新增项和删除项
	function diffArrays(oldArr, newArr) {
		// 提取有效的标识组合，比如 "type-requestType-itemType"
		function extractEntries(arr) {
			const result = new Set();
			arr.forEach((item) => {
				const mainType = item.type;
				if (item.requests) {
					item.requests.forEach((req) => {
						result.add(`${mainType}-${req.type}-${req.itemType}`);
					});
				} else {
					result.add(`${mainType}`);
				}
			});
			return result;
		}
	
		const oldSet = extractEntries(oldArr);
		const newSet = extractEntries(newArr);
	
		const added = [...newSet].filter((item) => !oldSet.has(item));
		const removed = [...oldSet].filter((item) => !newSet.has(item));
	
		// 可选：转回结构化对象形式
		function groupEntries(entries) {
			const grouped = {};
			for (const entry of entries) {
				const parts = entry.split('-');
				const mainType = parts[0];
				if (parts.length === 1) {
					grouped[mainType] = null; // 无 requests 的项
				} else {
					if (!grouped[mainType]) grouped[mainType] = [];
					grouped[mainType].push({
						type: parts[1],
						itemType: parts[2],
					});
				}
			}
	
			return Object.entries(grouped).map(([type, reqs]) => {
				return reqs === null ? { type } : { type, requests: reqs };
			});
		}
	
		return {
			added: groupEntries(added),
			removed: groupEntries(removed),
		};
	}
	
	//根据删除项删除数组
	function removeByDiff(flatList, removedItems) {
		// 先将 removedItems 也转为扁平集合
		const removeSet = new Set();
	
		removedItems.forEach((item) => {
			const mainType = item.type;
			if (item.requests) {
				item.requests.forEach((req) => {
					removeSet.add(`${mainType}-${req.itemType}`);
				});
			} else {
				removeSet.add(`${mainType}-null`);
			}
		});
	
		// 过滤掉需要删除的
		return flatList.filter((entry) => {
			const key = `${entry.type}-${entry.itemType}`;
			return !removeSet.has(key);
		});
	}
</script>

<template>
	<van-popup v-model:show="showBottom" round position="bottom"
		style="{ max-height: calc(100% - 100rpx);min-height:30%; }">
		<view class="h-full flex-col">
			<view class="flex-between list-p fz-32 text-color-1 pop-header">
				<view @click="close">取消</view>
				<view @click="commit">确认</view>
			</view>
			<view class="pop-content flex-1 ">
				<view class="h-full flex-center" v-if="!!menuData&&menuData.length<=0">
					<van-loading text-color="#0094ff" />
				</view>
				<view class="select-block" v-else>
				  <!-- 展示没有 detail 的 -->
				
				  <view  class="oneChecked fw-bold" v-for="category in menuData?.filter((item) => !(!!item.detail && item.detail.length >= 1))"
				      :key="category.type">
					  <van-checkbox
					    class="block ml-3"
					   
					    :name="category.type"
					    v-model="checkAllMap[category.type]"
					    @change="(val) => handleCheckAllChange(category.type, val, category.detail)"
					  >
					    {{ category.name }} ({{ category.count }})
					  </van-checkbox>
				  </view>
					<van-collapse v-model="activeName" accordion>
						<van-collapse-item
							v-for="category in menuData?.filter((item) => !!item.detail && item.detail.length >= 1)"
							:key="category.type" :name="category.type">
							<template #title>
								<view class="flex-start h-full ">
									<van-checkbox class="fw-bold" v-model="checkAllMap[category.type]"
										:indeterminate="isIndeterminateMap[category.type]" @click.stop
										@change="(val) => handleCheckAllChange(category.type, val, category.detail)">
										{{ category.name }}
									</van-checkbox>
								</view>
							</template>

							<van-checkbox-group v-model="selectedFilters[category.type]"
								@change="(val) => handleCheckboxChange(category.type, val)">
								<div v-for="item in category.detail" :key="item.itemType" class="checkbox-item">
									<van-checkbox shape="square" :name="item.itemType">
										{{ item.itemTypeName }}({{ item.itemCount }})
									</van-checkbox>
								</div>
							</van-checkbox-group>
						</van-collapse-item>
					</van-collapse>

				</view>

			</view>
		</view>


	</van-popup>

</template>

<style scoped lang="scss">
	.oneChecked{
		font-size: 14px;
		padding: 10px 0;
		margin: 0 16px;
		position: relative;
	}
	.oneChecked::after{
		border-bottom: 1px solid #ebedf0;
		transform: scaleY(.5);
		display: block;
		content: " ";
		width: 100%;
		padding: 0 16px;
		box-sizing: border-box;
		position: absolute;
		top: 0;
		pointer-events: none;
		
		
	}
	
	.pop-header {
		z-index: 9;
		background-color: white;
		position: sticky;
		left: 0;
		top: 0;
	}

	.select-block {
		width: 100%;

	}

	.checkbox-item {
		padding: 10rpx 0;
		margin-left: 32rpx;
	}
</style>